package userLimitService

import (
	"arabApi/app/api/models/userlimitModel"
	"arabApi/app/api/requests/userlimitRequest"
	"github.com/spf13/cast"
	"strings"
)

type Menu struct {
	ID       int
	ParentID int
	Label    string
	Children []Menu
}

type TreeList struct {
	ID       int        `json:"id"`
	ParentID int        `json:"parent_id"`
	Label    string     `json:"label"`
	Children []TreeList `json:"children"`
}

func RoleMenuAdd(r userlimitRequest.RoleMenuAdd) bool {
	id := cast.ToInt64(r.RoleId)

	ids := strings.Split(r.MenuIds, ",")
	um := make([]userlimitModel.RoleMenu, len(ids))
	for i, v := range ids {
		u := userlimitModel.RoleMenu{}
		u.RoleId = id
		u.MenuId = cast.ToInt64(v)
		um[i] = u
	}

	roleMenu := new(userlimitModel.RoleMenu)
	return roleMenu.RoleMenuAdd(id, um)
}

func Menu1() []TreeList {

	userroles := userlimitModel.MenuList1()

	menus := make([]Menu, len(userroles))

	for i, v := range userroles {
		m := Menu{}
		m.ParentID = cast.ToInt(v["p_id"])
		m.ID = cast.ToInt(v["id"])
		m.Label = cast.ToString(v["title"])
		menus[i] = m
	}

	ll := GetMenu(menus, 0)
	return ll
}

func RoleMenu(r string) []int {

	userroles := userlimitModel.MenuList2(cast.ToInt(r))

	ids := make([]int, len(userroles))

	for i, v := range userroles {
		ids[i] = cast.ToInt(v["menu_id"])
	}

	return ids
}

func FormMenu(list []Menu, pid int) (formMenu []Menu) {
	for _, val := range list {
		if val.ParentID == pid {
			if pid == 0 {
				// 顶层
				formMenu = append(formMenu, val)
			} else {
				var children []Menu
				child := val
				children = append(children, child)
			}
		}
	}
	return
}

func GetMenu(menuList []Menu, pid int) []TreeList {
	treeList := []TreeList{}
	for _, v := range menuList {
		if v.ParentID == pid {
			child := GetMenu(menuList, v.ID)
			node := TreeList{
				ID:       v.ID,
				Label:    v.Label,
				ParentID: v.ParentID,
			}
			node.Children = child
			treeList = append(treeList, node)
		}
	}
	return treeList
}
